package com.badger.spring.cloud.alibaba.consumer.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import feign.Client;
import feign.Feign;
import feign.Request;
import feign.Request.Options;
import feign.Response;
import feign.Retryer;
import io.seata.core.context.RootContext;

@Component
public class SeataFeignConfiguration {

    @Bean
    @Scope("prototype")
    public Feign.Builder feignBuilder() {
        return Feign.builder().client(seataClient()).retryer(Retryer.NEVER_RETRY);
    }

    public Client seataClient() {

        return new Client() {

            private final Client delegate = new Client.Default(null, null);

            @Override
            public Response execute(Request request, Options options) throws IOException {
                Request modifiedRequest = getModifyRequest(request);
                return this.delegate.execute(modifiedRequest, options);
            }

            @SuppressWarnings("deprecation")
            private Request getModifyRequest(Request request) {

                String xid = RootContext.getXID();

                if (StringUtils.isEmpty(xid)) {
                    return request;
                }

                Map<String, Collection<String>> headers = new HashMap<>();
                headers.putAll(request.headers());

                List<String> seataXid = new ArrayList<>();
                seataXid.add(xid);
                headers.put(RootContext.KEY_XID, seataXid);

                return Request.create(request.method(), request.url(), headers, request.body(), request.charset());
            }
        };
    }
}
